<?php
require_once 'app/bootstrap.php';

$agentRating = (int) (isset($_GET['agent_rating']) ? $_GET['agent_rating'] : 100);
$phone = (isset($_GET['phone']) ? $_GET['phone'] : null);
if ($phone) {
    $phone = str_replace('-', '', $phone);
    $phone = (int) str_replace(' ', '', $phone);
}

$helper = new Helper_CurrentDate;
$date = $helper->getCurrentDate();

$realtor = 0;
if (isset($_GET['realtor'])) {
    switch ($_GET['realtor']) {
        case 0:
        case 1:
            $realtor = (int) $_GET['realtor'];
            break;

        default:
            $realtor = null;
            break;
    }
}

$sectionId = (int) $_GET['section'];

try {
    $dbSection = new Model_Resource_SiteResource_Section();
    $section = $dbSection->find($sectionId)->current();
    if ($section == null) {
        header('Location: ' . DOMAIN);
        exit();
    }

    $dbAdvert = new Model_Resource_SiteResource_Section_Advert();
    $adverts = array();
    $phoneRelations = null;
    $phoneRow = null;
    if ($phone) {
        $dbPhone = new Model_Resource_Phone();
        $phoneRow = $dbPhone->fetchRowByPhone($phone);
        if ($phoneRow) {
            $phoneId = $phoneRow->id;
            $adverts = $dbAdvert->fetchAllWithPhones($sectionId, $agentRating, null, $phoneId);
            $dbPhoneRelations = new Model_Resource_Phone_Phone;
            $phoneRelations = $dbPhoneRelations->fetchAllWithPhones($phoneId);
        }

    } else {
        $adverts = $dbAdvert->fetchAllWithPhones($sectionId, $agentRating, $date, null, $realtor);
    }
} catch (Exception $e) {
    www($e->getMessage());
    www1($e->getTraceAsString());
}
require_once APPLICATION_PATH . '/view/page/header.phtml';
?>
<div class="grid_16">
    <h1><?php echo $section->section_title ?></h1>
    <p>
        <a href="index.php?<?php echo $helper->getQueryString()?>">&laquo;&laquo; <?php echo _('Back to sections list')?></a>
    </p>
</div>
<div class="clear" ></div>
<?php
if (date('D', strtotime($date)) == 'Sun') {
    echo _('No read ads at Sunday. Have a nice weekend! ;)');
    exit();
}?>
<?php if ($phoneRow) : ?>
    <script type="text/javascript"charset="UTF-8" language="JavaScript">
        $().ready(function(){
            $('.mark_as_realtor').click(function(){
                var el = $(this);
                $.ajax({
                    data:{phone: '<?php echo Helper_Advert::formatPhone($phone) ?>', realtor: '1'}
                    ,method:'get'
                    ,url:'mark.php'
                    ,success: function(response){
                        if (response == 'true') {
                            el.hide();
                            el.after('<span class="is_realtor"><?php echo _('Marked as realtor')?></span>');
                        }
                    }
                });
                return false;
            });
        });
    </script>
    <div class="grid_16">
        <h3>Adverts by phone: <span><?php echo Helper_Advert::formatPhone($phone) ?></span></h3>
        <p>
            <?php if ($phoneRow->realtor == 1) : ?>
            <span class="is_realtor"><?php echo _('Marked as realtor')?></span>
            <?php else : ?>
            <a href="#" class="mark_as_realtor"><?php echo _('Mark as realtor')?></a>
            <?php endif; ?>
        </p>
    </div>
    <div class="clear" ></div>
<?php endif; ?>
    <div class="grid_8">
        <div class="box" id="forms">
        <h2>
            <a id="toggle-search" href="#" class="hidden"  style="background-color:#993300;"><?php echo _('Filter')?></a>
        </h2>
        <div id="search" class="block" style="display: none;">
            <form method="get" action="adverts.php?">
                <fieldset>
                    <!--<legend><?php /*echo _('Filter')*/?></legend>-->
                    <input type="hidden" name="section" value="<?php echo $sectionId?>">
                    <input type="hidden" name="day" value="<?php echo $helper->getCurrentDay()?>">
                    <input type="hidden" name="month" value="<?php echo $helper->getCurrentMonth()?>">
                    <input type="hidden" name="year" value="<?php echo $helper->getCurrentYear()?>">
                    <p>
                        <label><?php echo _('Find word')?>: </label>
                        <input type="text" name="word" value="<?php echo @$_GET['word']?>">
                    </p>
                    <p>
                        <label><?php echo _('Advertiser has maximum X ads')?>:</label>
                        <input type="text" name="agent_rating" value="<?php echo $agentRating?>">
                    </p>
                    <p>
                        <label><?php echo _('Show all by phone')?>:</label>
                        <input type="text" name="phone" value="<?php echo Helper_Advert::formatPhone($phone)?>">
                    </p>
                    <?php if (!$phone) : ?>
                    <p>
                        <label><?php echo _('Realtor')?>:</label>
                        <select name="realtor">
                            <option value="2" <?php echo $realtor === 2 ? 'selected' : ''?>><?php echo _('All')?></option>
                            <option value="0" <?php echo $realtor === 0 ? 'selected' : ''?>><?php echo _('Don\'t show')?></option>
                            <option value="1" <?php echo $realtor === 1 ? 'selected' : ''?>><?php echo _('Only')?></option>
                        </select>
                    </p>
                    <?php endif; ?>
                    <input type="submit">
                </fieldset>
            </form>
        </div>
        </div>
    </div>
<div class="grid_8">
    <?php require_once APPLICATION_PATH . '/view/page/date.phtml';?>
</div>
<div class="clear"></div>

<div style="overflow:hidden;">
<?php
$i = 0;
/** @var $item Zend_Db_Table_Row */
foreach ($adverts as $item) :
    $cost = null;

    $word = mb_strtolower(trim(@$_GET['word']), 'utf-8');
    $advertLower = mb_strtolower($item['advert'], 'utf-8');
    if ($word && strpos($advertLower, $word) === false)
        continue;

    $item['phones']         = explode(', ', $item->phones);
    $phones                 = explode(', ', $item->rating_phones);
    foreach ($phones as $key => $phone) {
        $phones[$key] = Helper_Advert::formatPhone($phone);
    }
    $item->rating_phones = $phones;

    $cnt = count($item['phones']);
    ?>
    <div class="grid_4">
        <div class="block">
            <?php echo $item['advert']?>
            <br>
            <b class="agent_rating <?php echo $item['realtor'] ? 'is_realtor' : '' ?>">
            <?php printf(_('Advertiser has %s ads'), $item['realtor_rating']) ?></b>
            <br>
            <span class="adt_phones">Phones:
                <?php foreach ($item['phones'] as $key => $phone) : ?>
                    <a href="adverts.php?section=<?php echo $sectionId ?>&phone=<?php echo $phone ?><?php echo $helper->getQueryString()?>"><?php
                        echo $item['rating_phones'][$key] ;
                    ?></a><?php echo ($key + 1 < $cnt) ? ', ' : '' ?>
                    <?php endforeach;?>
            </span>
            <br>
            <span class="adt_date">
                <?php echo _('Created at')?>: <?php echo $item['created_at'] ?>
                <?php if ($item['last_repeat_at']) : ?>
                / <?php echo _('Last repeated at')?>: <?php echo $item['last_repeat_at'] ?>
                <?php endif; ?>
            </span>
            <br>
        </div>
    </div>
    <?php
    $i++;
    if (!($i % 4)) : ?>
        <br clear="left">
        <div class="" style="text-align:left;border-top:1px #cccccc dashed; margin-top:10px"></div>
    <?php
    endif;
endforeach;
?>
</div>

<?php if ($phoneRelations) : ?>
<div class="box phone_relations" style="margin-bottom:0">
    <p>
    <?php if (false !== ($cnt = $phoneRelations->count()) && $cnt > 0) : ?>
            <label><?php echo _('Phone relations')?>:</label>
            <?php foreach ($phoneRelations as $key => $phoneRow) : ?>
            <a href="adverts.php?section=<?php echo $sectionId ?>&phone=<?php echo $phoneRow->phone ?><?php echo $helper->getQueryString()?>"><?php
                    echo $phoneRow->phone;
                echo " ({$phoneRow->count_advert})";
                if ($key + 1 < $cnt) :
                    echo ',';
                endif;
                ?></a>
            <?php endforeach; ?>
        <?php else: ?>
            <?php echo _('No any phone relations'); ?>
        <?php endif; ?>
    </p>
</div>
<?php endif; ?>
